package org.jeecg.modules.wlhy.customer.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.Acc;
import org.jeecg.modules.paycenter.channel.bankdocking.dto.RespPacket;
import org.jeecg.modules.paycenter.channel.bankdocking.utils.BankUtils;
import org.jeecg.modules.paycenter.service.WalletService;
import org.jeecg.modules.wlhy.bill.entity.HyCustomerBill;
import org.jeecg.modules.wlhy.bill.service.IHyCustomerBillService;
import org.jeecg.modules.wlhy.customer.entity.HyCustomer;
import org.jeecg.modules.wlhy.customer.entity.HyCustomerAccountBook;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerAccountBookService;
import org.jeecg.modules.wlhy.customer.service.IHyCustomerService;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hycustomerbank.entity.HyCustomerBank;
import org.jeecg.modules.wlhy.hycustomerbank.service.IHyCustomerBankService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecg.modules.wlhy.walletcfg.service.IHyWalletCfgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

 /**
 * @Description: hy_customer_account_book
 * @Author: jeecg-boot
 * @Date:   2021-01-15
 * @Version: V1.0
 */
@Api(tags="hy_customer_account_book")
@RestController
@RequestMapping("/customer/hyCustomerAccountBook")
@Slf4j
public class HyCustomerAccountBookController extends JeecgController<HyCustomerAccountBook, IHyCustomerAccountBookService> {
	@Autowired
	private IHyCustomerAccountBookService hyCustomerAccountBookService;

	 @Autowired
	 private IHyShippingNoteService hyShippingNoteService;

	 @Autowired
	 private UserUtil userUtil;

//	 @Autowired
//	 private BankUtils bankUtils;

	 @Autowired
	 private RedisUtil redisUtil;

	 @Autowired
	 private IHyCustomerService hyCustomerService;

	 @Autowired
	 private IHyCustomerBankService hyCustomerBankService;
	 @Autowired
	 private IHySettingService settingService;

	 @Autowired
	 private IHyCustomerBillService hyCustomerBillService;

	 @Autowired
	 private BankUtils bankUtils;

	 @Autowired
	 private WalletService walletService;
	 @Value("${pay-config.trade.begin:8}")
	 private String TRADE_BEGIN;

	 @Value("${pay-config.trade.end:19}")
	 private String TRADE_END;

	 @Value("${pay-config.cash-out.active:1}")
	 private String CASHOUT_ACTIVE;

	 @Value("${pay-config.cash-out.begin:8}")
	 private String CASHOUT_BEGIN;

	 @Value("${pay-config.cash-out.end:19}")
	 private String CASHOUT_END;

	 @Value("${pay-config.sms-active:0}")
	 private String CASH_OUT_SMS_ACTIVE;

	 @Value("${pay-config.acc-sms-active:0}")
	 private String ACC_SMS_ACTIVE;

	 @ApiOperation(value="获取货主多级账簿信息", notes="获取货主多级账簿信息")
	 @GetMapping(value = "/getAccountBookInfo")
	 public Result<?> getAccountBookInfo() throws Exception {
		 Map data =  hyCustomerAccountBookService.getAccountBookInfo();
		 return Result.OK(data);
	 }



	 @ApiOperation(value="获取货主账户信息", notes="获取货主账户信息")
	 @GetMapping(value = "/getAcc")
	 public Result<?> getAcc() {
		 Map data =  hyCustomerAccountBookService.getAcc();
		 return Result.OK(data);
	 }

	 @AutoLog(value = "开通多级账簿")
	 @ApiOperation(value="开通多级账簿", notes="开通多级账簿")
	 @PostMapping(value = "/addAccountBook")
	 @RequiresPermissions("customer:addAccountBook")
	 public Result<?> addAccountBook(@RequestBody HyCustomerAccountBook hyCustomerAccountBook) {
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 HyConfig config = HyConfigUtils.getConfig();
		 if(!config.getNhbankIzUse()){
			 return Result.error("未开通服务！");
		 }
		 hyCustomerAccountBookService.addAccountBook(hyCustomerAccountBook);
		 return Result.OK("添加成功！");
	 }

	 @ApiOperation(value="获取货主多级账簿信息", notes="获取货主多级账簿信息")
	 @GetMapping(value = "/getAccountBookByCustomerId")
	 public Result<?> getAccountBookByCustomerId(@RequestParam(name="id",defaultValue = "") String customerId) throws Exception {
	 	 if(StringUtils.isEmpty(customerId)){
			 return Result.error("数据不存在");
		 }
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 HyCustomerAccountBook hyCustomerAccountBook = hyCustomerAccountBookService.getAccountBookByCustomerId(customerId);
		 if(hyCustomerAccountBook != null){
			 Acc customerAcc = hyCustomerAccountBookService.getCustomerAcc(hyCustomerAccountBook);
			 if(customerAcc != null){
				 BigDecimal amt = customerAcc.getAvailBal();
				 hyCustomerAccountBook.setAmt(amt);
				 hyCustomerAccountBook.setAccSts(customerAcc.getAccSts());
				 hyCustomerAccountBookService.updateById(hyCustomerAccountBook);
			 }else {
				 hyCustomerAccountBook.setAmt(BigDecimal.ZERO);
				 hyCustomerAccountBook.setAccSts("-99");
			 }
			 hyCustomerAccountBook.setPayPwd("");
			 hyCustomerAccountBook.setFrzAmt(BigDecimal.ZERO);
//			 BigDecimal djsAmt = hyCustomerAccountBookService.getDJSByCustomerId(customerId);
			 BigDecimal djsAmt = hyShippingNoteService.getCustomerDjsFee(customerId);
			 hyCustomerAccountBook.setAvailAmt(djsAmt);//余额替换为 待结算金额
			 HyConfig config = HyConfigUtils.getConfig();
			 String nhbankBankname = "";
			 if (config != null) {
				 nhbankBankname = config.getNhbankBankname();
			 }
			 hyCustomerAccountBook.setKhh(nhbankBankname);
			 return Result.OK(hyCustomerAccountBook);
		 }
		 return Result.OK(hyCustomerAccountBook);
	 }

	 @AutoLog(value = "管理员开通多级账簿")
	 @ApiOperation(value="管理员开通多级账簿", notes="管理员开通多级账簿")
	 @PostMapping(value = "/addAccountBookByCustomerId")
	 @Transactional
	 public Result<?> addAccountBookByCustomerId(@RequestBody JSONObject jo) {
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 String customerId = jo.getString("id");
		 if(StringUtils.isEmpty(customerId)){
			 return Result.error("数据不存在");
		 }
		 if(!userUtil.isSys()){
			 return Result.error("没有权限！");
		 }
		 String settingValue = settingService.getSettingValueByTag("bank_relative");
		 if(!"1".equals(settingValue)) {
			 throw new JeecgBootException("系统暂时关闭支付功能");
		 }

		 HyConfig config = HyConfigUtils.getConfig();
		 if(!config.getNhbankIzUse()){
			 return Result.error("未开通服务！");
		 }

		 String nhbankAccName = config.getNhbankAccName();
		 if(StringUtils.isEmpty(nhbankAccName)){
			 return Result.error("未配置农行账户名称！");
		 }

		 HyCustomer customer = hyCustomerService.getById(customerId);
		 if(customer == null){
			 return Result.error("货主信息不存在！");
		 }
		 HyCustomerAccountBook customerAccountBook = hyCustomerAccountBookService.getAccountBookByCustomerId(customerId);
		 if(customerAccountBook != null){
			 return Result.error("不能重复开通！");
		 }

		 HyCustomerAccountBook hyCustomerAccountBook = new HyCustomerAccountBook();
		 String logAccNo =  hyCustomerAccountBookService.createCustomerLogAccNo();
//		 String logAccName = customer.getCustomerName();
		 String logAccName = nhbankAccName;
		 hyCustomerAccountBook.setCustomerId(customer.getId());
		 hyCustomerAccountBook.setUserId(customer.getUserId());
		 hyCustomerAccountBook.setAccNo(config.getNhbankAccno());
		 hyCustomerAccountBook.setProv(config.getNhbankProv());
		 hyCustomerAccountBook.setLogAccName(nhbankAccName);
		 hyCustomerAccountBook.setLogAccNo(logAccNo);
//        hyCustomerAccountBook.setCrLogAccNo("0000000000");
//        hyCustomerAccountBook.setLogAccNoGr("");
		 String payPwd = "123456";
		 String encryptPayPwd = PasswordUtil.encrypt(logAccNo, payPwd,  PasswordUtil.BSalt);
		 hyCustomerAccountBook.setPayPwd(encryptPayPwd);
		 if( hyCustomerAccountBookService.save(hyCustomerAccountBook)){
			 try {
				 RespPacket packet = bankUtils.AddAccountBook(nhbankAccName, logAccNo);
				 if(!packet.isSuccess()){
					 throw new JeecgBootException(packet.getRespInfo());
				 }
			 } catch (Exception e) {
				 throw new JeecgBootException(e.getMessage());
			 }
		 }else {
			 throw new JeecgBootException("添加失败");
		 }
		 return Result.OK("添加成功！");
	 }

	 @AutoLog(value = "设置支付密码")
	 @ApiOperation(value="设置支付密码", notes="设置支付密码")
	 @PostMapping(value = "/setpwd")
	 @RequiresPermissions("customer:setpwd")
	 public Result<?> setpwd(@RequestBody JSONObject jsonObject) {
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 String oldPwd = jsonObject.getString("oldpassword");
		 String password = jsonObject.getString("password");
		 if(StringUtils.isEmpty(oldPwd)){
			 return Result.error("原始支付密码不能为空！");
		 }
		 if(StringUtils.isEmpty(password)){
			 return Result.error("新支付密码不能为空！");
		 }
		 //验证支付密码
		 hyCustomerAccountBookService.editPayPwd(oldPwd,password);
		 return Result.OK("修改成功！");
	 }

	 @AutoLog(value = "设置支付密码")
	 @ApiOperation(value="设置支付密码", notes="设置支付密码")
	 @PostMapping(value = "/resetpwd")
	 @RequiresPermissions("customer:resetpwd")
	 public Result<?> resetpwd(@RequestBody JSONObject jsonObject) {
		 if (DateUtil.hour(new Date(), true)>Integer.parseInt(TRADE_END) || DateUtil.hour(new Date(), true) < Integer.parseInt(TRADE_BEGIN)){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 String captcha = jsonObject.getString("captcha");
		 String password = jsonObject.getString("password");
		 if(StringUtils.isEmpty(captcha)){
			 return Result.error("验证码！");
		 }
		 if(StringUtils.isEmpty(password)){
			 return Result.error("新支付密码不能为空！");
		 }
		 LoginUser loginUser = UserUtil.getLoginUser();
		 if(loginUser == null){
			 return Result.error("未获取到登录信息");
		 }
		 String phone = loginUser.getPhone();
		 Object code = redisUtil.get(phone);
		 if (!captcha.equals(code)) {
			 return Result.error("验证码错误");
		 }
		 //验证支付密码
		 hyCustomerAccountBookService.ResetPayPwd(password);
		 return Result.OK("修改成功！");
	 }


	 @AutoLog(value = "货主提现")
	 @ApiOperation(value="货主提现", notes="货主提现")
	 @PostMapping(value = "/tx")
	 @RequiresPermissions("customer:tx")
	 public Result<?> tx(@RequestBody JSONObject jsonObject) {
		 if ("1".equalsIgnoreCase(CASHOUT_ACTIVE)
				 &&( DateUtil.hour(new Date(), true)>Integer.parseInt(CASHOUT_END) || DateUtil.hour(new Date(), true) <Integer.parseInt(CASHOUT_BEGIN))){
			 return Result.error("不在交易时间内, 详情请咨询系统管理员！");
		 }


		 HyConfig config = HyConfigUtils.getConfig();
		 if (!config.getNhbankIzUse()) {
			 return Result.error("未开通服务！");
		 }

		 String settingValue = settingService.getSettingValueByTag2("bank_relative");
		 if(!"1".equals(settingValue)) {
			 return Result.error("系统暂时关闭支付功能！");
		 }

		 String pwd = jsonObject.getString("pwd");
		 String customerBankId = jsonObject.getString("customerBankId");
		 String samt = jsonObject.getString("amt");

		 if(StringUtils.isEmpty(pwd)){
			 return Result.error("支付密码不能为空！");
		 }
		 if(StringUtils.isEmpty(customerBankId)){
			 return Result.error("请选择银行卡！");
		 }
		 if(StringUtils.isEmpty(samt)){
			 return Result.error("提现金额不能为空！");
		 }
		 BigDecimal amt = null;
		 try{
			 amt = new BigDecimal(samt);
		 }catch (Exception e){
			 return Result.error("提现金额格式错误！");
		 }
		 // 0 > amt
		 if(BigDecimal.ZERO.compareTo(amt) == 1){
			 return Result.error("提现金额错误！");
		 }

		 boolean isSys = userUtil.isSys();
		 HyCustomer customer = null;
		 if(isSys){
			 if(!walletService.checkPwd(pwd)){
				 return Result.error("支付密码错误");
			 }

			 String customerId = jsonObject.getString("customerId");
			 if(StringUtils.isEmpty(customerId)){
				 return Result.error("货主不能为空！");
			 }
			 customer = hyCustomerService.getById(customerId);
		 }else {
			 customer = userUtil.getCustomer();
		 }
		 if(customer==null){
			 return Result.error("货主信息不存在!");
		 }
		 HyCustomerBank customerBank = hyCustomerBankService.getById(customerBankId);
		 if(customerBank == null){
			 return Result.error("银行卡信息不存在!");
		 }
		 if(!StringUtils.equals(customerBank.getCustomerId() , customer.getId())){
			 return Result.error("银行卡信息错误!");
		 }

		 //验证支付密码
		 HyCustomerAccountBook customerAccountBook = hyCustomerAccountBookService.getAccountBookByCustomerId(customer.getId());
		 if (customerAccountBook == null) {
			 return Result.error("尚未开通钱包功能!");
		 }
		 if(!isSys) {
			 if(!walletService.checkPwd(pwd)){
				 return Result.error("支付密码错误");
			 }
		 }
		 //检查货主运费是否够支付
		 Acc customerAcc = hyCustomerAccountBookService.getCustomerAcc(customerAccountBook);
		 if (customerAcc == null) {
			 return Result.error("查询余额失败");
		 }
		 //可用余额
		 BigDecimal availBal = customerAcc.getAvailBal();
		 if (amt.compareTo(availBal) == 1) {
			 return Result.error("账户余额不足");
		 }
		 //提现
		 Result r = hyCustomerAccountBookService.tx(customer,customerAccountBook,customerBank,amt);
		 return r;
	 }

	 @AutoLog(value = "货主查询交易状态")
	 @ApiOperation(value="货主查询交易状态", notes="货主查询交易状态")
	 @PostMapping(value = "/exchangeStatus")
	 @RequiresPermissions("customer:tx")
	 public Result<?> exchangeStatus(@RequestBody JSONObject jsonObject) {
		 String settingValue = settingService.getSettingValueByTag2("bank_relative");
		 if(!"1".equals(settingValue)) {
			 return Result.error("系统暂时关闭支付功能！");
		 }

		 HyConfig config = HyConfigUtils.getConfig();
		 if (!config.getNhbankIzUse()) {
			 return Result.error("未开通服务！");
		 }

		 String customerBillid = jsonObject.getString("id");
		 if(StringUtils.isEmpty(customerBillid)){
			 return Result.error("数据不存在！");
		 }

		 HyCustomerBill customerBill = hyCustomerBillService.getById(customerBillid);
		 if(customerBill == null){
			 return Result.error("数据不存在！");
		 }

		 if(!userUtil.isSys()){
			 HyCustomer customer = userUtil.getCustomer();
			 if(customer==null){
				 return Result.error("货主信息不存在!");
			 }
			 if(!StringUtils.equals(customer.getId() , customerBill.getCustomerId())){
				 return Result.error("数据错误！");
			 }
		 }
		 hyCustomerAccountBookService.exchangeStatus(customerBill);
		 return Result.OK(customerBill);
	 }

//	/**
//	 * 分页列表查询
//	 *
//	 * @param hyCustomerAccountBook
//	 * @param pageNo
//	 * @param pageSize
//	 * @param req
//	 * @return
//	 */
//	@AutoLog(value = "hy_customer_account_book-分页列表查询")
//	@ApiOperation(value="hy_customer_account_book-分页列表查询", notes="hy_customer_account_book-分页列表查询")
//	@GetMapping(value = "/list")
//	public Result<?> queryPageList(HyCustomerAccountBook hyCustomerAccountBook,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//		QueryWrapper<HyCustomerAccountBook> queryWrapper = QueryGenerator.initQueryWrapper(hyCustomerAccountBook, req.getParameterMap());
//		Page<HyCustomerAccountBook> page = new Page<HyCustomerAccountBook>(pageNo, pageSize);
//		IPage<HyCustomerAccountBook> pageList = hyCustomerAccountBookService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}


//	/**
//	 *  编辑
//	 *
//	 * @param hyCustomerAccountBook
//	 * @return
//	 */
//	@AutoLog(value = "hy_customer_account_book-编辑")
//	@ApiOperation(value="hy_customer_account_book-编辑", notes="hy_customer_account_book-编辑")
//	@PutMapping(value = "/edit")
//	public Result<?> edit(@RequestBody HyCustomerAccountBook hyCustomerAccountBook) {
//		hyCustomerAccountBookService.updateById(hyCustomerAccountBook);
//		return Result.OK("编辑成功!");
//	}
//
//	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_customer_account_book-通过id删除")
//	@ApiOperation(value="hy_customer_account_book-通过id删除", notes="hy_customer_account_book-通过id删除")
//	@DeleteMapping(value = "/delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		hyCustomerAccountBookService.removeById(id);
//		return Result.OK("删除成功!");
//	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "hy_customer_account_book-批量删除")
//	@ApiOperation(value="hy_customer_account_book-批量删除", notes="hy_customer_account_book-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyCustomerAccountBookService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}
//
//	/**
//	 * 通过id查询
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "hy_customer_account_book-通过id查询")
//	@ApiOperation(value="hy_customer_account_book-通过id查询", notes="hy_customer_account_book-通过id查询")
//	@GetMapping(value = "/queryById")
//	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
//		HyCustomerAccountBook hyCustomerAccountBook = hyCustomerAccountBookService.getById(id);
//		if(hyCustomerAccountBook==null) {
//			return Result.error("未找到对应数据");
//		}
//		return Result.OK(hyCustomerAccountBook);
//	}
//
//    /**
//    * 导出excel
//    *
//    * @param request
//    * @param hyCustomerAccountBook
//    */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, HyCustomerAccountBook hyCustomerAccountBook) {
//        return super.exportXls(request, hyCustomerAccountBook, HyCustomerAccountBook.class, "hy_customer_account_book");
//    }
//
//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyCustomerAccountBook.class);
//    }

}
